package cn.gwm.utils;

import cn.gwm.flink.streaming.business.ModuleConfData;
import cn.gwm.flink.streaming.config.GlobalConfig;
import cn.gwm.flink.streaming.constant.BusinessUrl;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: liangguang
 * @Date: 2023/02/18
 * @Description: 全局配置 查询
 */
@Slf4j
public class GlobalConfigUtil {

    public static final String BUSINESS_STATION_URL = ConfigLoader.get("charging.station.type.url");

    /**
     * 更新 充电配置
     */
    public static void requestConfig(String topic, GlobalConfig[] configs) {
        Map<String, Object> param = new HashMap<>();
        param.put("topics", topic);
        try {
            String s = HttpUtil.get(BUSINESS_STATION_URL + BusinessUrl.PUBLIC_CONFIGURATION, param);
            JSONObject parseObj = JSONUtil.parseObj(s);
            if (parseObj.getInt("code") == 200) {
                JSONArray resultData = parseObj.getJSONArray("data");
                resultData.forEach(item -> {
                    JSONObject obj = JSONUtil.parseObj(item);
                    for (GlobalConfig config : configs) {
                        if (config.getName().equals(obj.get("configKey"))) {
                            config.setValue(obj.getStr("configValue"));
                            break;
                        }
                    }
                });

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("update charge config happen error :" + e.getMessage() + "StackTrace={}", e.getStackTrace());
        }
    }

    /**
     * 获取服务功能配置
     */
    public static List<ModuleConfData.ModuleConf> requestModuleConfigList() {
        Map<String, Object> param = new HashMap<>();
        List<ModuleConfData.ModuleConf> confList = new ArrayList<>();
        try {
            String s = HttpUtil.post(BUSINESS_STATION_URL + BusinessUrl.BUSINESS_MODULE_LIST_GET, JSONUtil.toJsonStr(param));
            JSONObject parseObj = JSONUtil.parseObj(s);
            if (parseObj.getInt("code") == 200) {
                JSONArray resultData = parseObj.getJSONArray("data");
                resultData.forEach(item -> {
                    JSONObject obj = JSONUtil.parseObj(item);
                    ModuleConfData.ModuleConf moduleConf = JSONUtil.toBean(obj, ModuleConfData.ModuleConf.class);
                    confList.add(moduleConf);
                });
                return confList;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("update module config happen error :" + e.getMessage() + "StackTrace={}", e.getStackTrace());
        }
        return confList;
    }
}
